package com.gxy.learn.backup.shiroauth.common.exception;

import com.gxy.learn.backup.shiroauth.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final String url = "url";
    private static final String errorMsg = "errorMsg";


    /**
     * 捕捉404异常
     *
     * @return
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handle(HttpServletRequest req, NoHandlerFoundException ex) {
        log.error("{}:{},{}:{}", url,req.getRequestURI(), errorMsg,ex.getMessage(), ex);
        return Result.error("未知的请求！");
    }

    /**
     * 捕捉其他所有异常
     *
     * @param req
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result globalException(HttpServletRequest req, Throwable ex) {
        log.error("{}:{},{}:{}", url,req.getRequestURI(), errorMsg,ex.getMessage(), ex);
        return Result.error("请求出现异常！");
    }


    /**
     * login登录时 捕捉异常
     * 捕捉500异常
     *
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(IncorrectCredentialsException.class)
    public Result handle(HttpServletRequest req, IncorrectCredentialsException ex) {
        log.error("{}:{},{}:{}", url,req.getRequestURI(), errorMsg,ex.getMessage(), ex);
        return Result.error("登录失败！用户名密码错误！");
    }

    /**
     * login登录时 捕捉异常
     * 捕捉500异常
     *
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(UnknownAccountException.class)
    public Result handle(HttpServletRequest req, UnknownAccountException ex) {
        log.error("{}:{},{}:{}", url,req.getRequestURI(), errorMsg,ex.getMessage(), ex);
        return Result.error("登录失败！未知的用户！");
    }
}
